import asyncio
from fastapi import FastAPI, APIRouter
from typing import Dict
import uvicorn

Default_Config = {
    "host": "127.0.0.1",
    "port": 8090,
    "log_level": "info",
}


# 1. 创建基于类的视图
class httpServer_Fastapi:
    def __init__(self, config):
        # 1.创建app (fastapi示例), router路由
        self.app = FastAPI(title="FastAPI Class-Based Views Example")
        self.router = APIRouter()

        # 2. 类初始化
        self.config = config
        self.count = 0
        # 3. 注册路由
        self.router.add_api_route("/", self.index_html, methods=["GET"], response_model=Dict[str, str])

        # 4.路由注册到app
        self.app.include_router(self.router)
        # 5.配置,启动服务
        self.init_server()

    def init_server(self):
        self.uvicorn_config = uvicorn.Config(
            self.app,
            host=self.config["host"],
            port=self.config["port"],
            timeout_keep_alive=16,
            log_level=self.config["log_level"],
        )
        self.server = uvicorn.Server(self.uvicorn_config)

    async def async_loop_run(self):
        await self.server.serve()

    # 路由处理方法
    def index_html(self):
        self.count += 1
        return {"Hello": f"count={self.count}"}


async def main():
    http_server = httpServer_Fastapi(Default_Config)
    await http_server.async_loop_run()


if __name__ == "__main__":
    asyncio.run(main())

""" 
不带前缀: http://localhost:8090/
带前缀: http://localhost:8090/users/
"""
